{% extends 'form_div_layout.html.twig' %}

{% block form_row %}
{% spaceless %}
	<div class="box">
		{{ form_label(form) }}
		{{ form_widget(form) }}
		{{ form_errors(form) }}
	</div>
{% endspaceless %}
{% endblock form_row %}

{% block textarea_widget %}
	<textarea {{ block('widget_attributes') }}>{{ value }}</textarea>
	<script>
		$(function() {
			$('#{{ id }}').parent().css('width', '100%');
		});
	</script>
{% endblock textarea_widget %}

{% block choice_widget_expanded -%}
		<style>
			.mlc-pane { float: left; width: 200px; }
			.mlc-pane label { width: 80%; display: inline-block; padding-left: 10px; }
		</style>
    <div {{ block('widget_container_attributes') }}>
    {%- for child in form %}
    		<div class="mlc-pane">
        	{{- form_widget(child) -}}
        	{{- form_label(child) -}}
        </div>
    {% endfor -%}
    <script>
			$(function() {
				$('#{{ id }}').parent().css('width', '100%');
			});
		</script>
    </div>
{% endblock choice_widget_expanded %}

{% block checkbox_widget -%}
    <input type="checkbox" {{ block('widget_attributes') }}{% if value is defined %} value="{{ value }}"{% endif %}{% if checked %} checked="checked"{% endif %} />
{%- endblock checkbox_widget %}

{% block form_errors %}
	{% if errors|length > 0 %}
		{% for error in errors %}
			<div class="error">{{ error.message }}</div>
		{% endfor %}
	{% endif %}
{% endblock form_errors %}

{% block ckeditor_widget %}
	<textarea class="ckeditor" {{ block('widget_attributes') }}>{{ value }}</textarea>
	<script>
		$(function() {
			$('#{{ id }}').parent().css('width', '100%');
		});
	</script>
{% endblock ckeditor_widget %}

{% block filepicker_widget %}
	<div id="preview" onclick="$('#{{ id }}').click();"><img src="/secret/assets/image/{{ value|split('/')|last|split('.')|first }}/290/?r={{ random() }}"></img></div>
	<input type="{{ type }}" {{ block('widget_attributes') }} style="display: none;" onchange="handleFiles(this.files);" />
	<button onclick="$('#{{ id }}').click(); return false;" class="button bg-yellow">Replace file ›</button>
	<script>
		{% if value == '' or value == null %}
		$(function() {
			$('#{{ id }}').parent().remove();
		});
		{% endif %}
		
		function handleFiles(files) {
			var preview = document.getElementById("preview");
				for (var i = 0; i < files.length; i++) {
					var file = files[i];
					var imageType = /image.*/;
// 					$('#file-name').html(file.name);
// 					$('#file-type').html(file.type);
// 					$('#file-size').html((file.size / 1000).toFixed(2));
					if (!file.type.match(imageType)) {
// 						$('#preview').find('img').attr('src', '/cms/html/files/images/shadow.gif');
// 						$('#preview').find('img').css('width', '600px');
// 						$('#preview').find('img').css('height', '250px');
						continue;
					}
					$('#preview').empty();
					var img = document.createElement("img");
					img.classList.add("obj");
					img.file = file;
					preview.appendChild(img); // Assuming that "preview" is a the div output where the content will be displayed.
					var reader = new FileReader();
					reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
					reader.readAsDataURL(file);
			}
		} 
	</script>
{% endblock filepicker_widget %}

{% block cbml_widget %}
	<div id="container{{ id }}"></div>
	<button onclick="add{{ id }}(event);">Add content section</button>
	<input type="hidden" value="{{ (value and value != '') ? value : '[]' }}" {{ block('widget_attributes') }} />
	<script>
		{% set langs = app.generic.modelData('Language', '', {}, { sort: 'rank', order: 'ASC' }) %}
		var _langs{{ id }} = {{ langs|json_encode|raw }};
		
		$(function() {
			if (!window._updates) {
				window._updates = [];
			}
			window._updates.push(update{{ id }});
			
			$('#{{ id }}').parent().prepend('<div>&nbsp</div>');
			$('#{{ id }}').parent().append('<div>&nbsp</div>');
			$('#{{ id }}').parent().css('width', '100%');
			repaint{{ id }}();
		});

		function add{{ id }}(ev) {
			ev.preventDefault();
			values = [];
			try {
				var values = JSON.parse($('#{{ id }}').val());
			} catch (ex) {}
			var obj = {
				title: '',
				blocks: {},
			};
			for (var idx in _langs{{ id }}._data) {
				var itm = _langs{{ id }}._data[idx];
				obj.blocks[itm.urlFragment] = '';
			}
			values.push(obj);
			$('#{{ id }}').val(JSON.stringify(values));
			repaint{{ id }}();
		};

		function repaint{{ id }}() {
			$('#container{{ id }}').empty();
			values = [];
			try {
				var values = JSON.parse($('#{{ id }}').val());
			} catch (ex) {}
			for (var idx in values) {
				var itm = values[idx];
				$('#container{{ id }}').append(
					'<div>' +
						'<div class="example" style="width: 100%;">' +
							'<i style="float: right; cursor: pointer;" class="fa fa-times" onclick="remove{{ id }}(' + idx + ')"></i>' +
							'<label>Heading</label>' +
							'<input onchange="update{{ id }}();" type="text" name="title{{ id }}' + idx + '" style="width: 100%; margin-bottom: 15px;" value="' + itm.title + '"/>' +
							'<div class="tab-control">' +
								'<ul id="tabs{{ id }}' + idx + '" class="tabs"></ul>' + 
								'<div id="frames{{ id }}' + idx + '"class="frames"></div>' +
							'</div>' +
						'</div>' +
					'</div>'
				);
				for (var idx2 in _langs{{ id }}._data) {
					var itm2 = _langs{{ id }}._data[idx2];
					$('#tabs{{ id }}' + idx).append(
						'<li ' + ((idx2 == 0) ? 'class="active"' : '') + '>' +
							'<a href="#_page_{{ id }}' + idx + idx2 + '">' + itm2.title + '</a>' +
						'</li>'
					);
					
					var content = '';
					for (var idx3 in itm.blocks) {
						var itm3 = itm.blocks[idx3];
						if (itm3[itm2.urlFragment] != undefined) {
							content = itm3[itm2.urlFragment];
						}
					}
					$('#frames{{ id }}' + idx).append(
						'<div id="_page_{{ id }}' + idx + idx2 + '" class="frame">' +
							'<textarea class="ckeditor{{ id }}" data-lang="' + itm2.urlFragment + '" name="content{{ id }}' + idx + idx2 + '">' + content + '</textarea>' +
						'</div>'
					);
				}
			}
			
			$('.tab-control').tabcontrol();
//			$('#container{{ id }}').sortable();
			$('textarea').css('resize', 'vertical');
			$.each($('.ckeditor{{ id }}'), function(key, value) {
				CKEDITOR.replace($(value).attr('name'), {
					filebrowserBrowseUrl: '/secret/assets/?view=ckeditor',
					extraPlugins: 'autogrow',
				});
			});
			CKEDITOR.on("instanceReady", function(event) {
				event.editor.execCommand( 'autogrow' );
			});

			for (var i in CKEDITOR.instances) {
        CKEDITOR.instances[i].on('key', function() { setTimeout( function() { update{{ id }}(); }, 500); });
    	}
		};
		
		function remove{{ id }}(index) {
			var values = JSON.parse($('#{{ id }}').val());
			values.splice(index, 1);
			$('#{{ id }}').val(JSON.stringify(values));
			repaint{{ id }}();
		};

		function update{{ id }}() {
			var result = [];
			$.each($('#container{{ id }}').children(), function(key, value) {
				var obj = {};
				obj.title = $(value).find('[name=title{{ id }}' + key + ']').val();
				obj.blocks = [];
				var block = {};
				$.each($(value).find('div.frames').children(), function(key, value) {
					block[$(value).find('textarea').attr('data-lang')] = CKEDITOR.instances[$(value).find('textarea').attr('name')].getData();
				});
				obj.blocks.push(block);
				result.push(obj);
			});
			$('#{{ id }}').val(JSON.stringify(result));
		};
	</script>
{% endblock cbml_widget %}

{% block cml_widget %}
	<div id="container{{ id }}"></div>
	<input type="hidden" value="{{ (value and value != '') ? value : '[]' }}" {{ block('widget_attributes') }} />
	<script>
		{% set langs = app.generic.modelData('Language', '', {}, { sort: 'rank', order: 'ASC' }) %}
		var _langs{{ id }} = {{ langs|json_encode|raw }};
		
		$(function() {
			if (!window._updates) {
				window._updates = [];
			}
			window._updates.push(update{{ id }});
			
			$('#{{ id }}').parent().prepend('<div>&nbsp</div>');
			$('#{{ id }}').parent().append('<div>&nbsp</div>');
			$('#{{ id }}').parent().css('width', '100%');
			
			values = [];
			try {
				var values = JSON.parse($('#{{ id }}').val());
			} catch (ex) {}
			if (values.length == 0) {
				var obj = {
					title: '',
					blocks: [],
				};
				var block = {};
				for (var idx in _langs{{ id }}._data) {
					var itm = _langs{{ id }}._data[idx];
					block[itm.urlFragment] = '';
				}
				obj.blocks.push(block);
				values.push(obj);
				$('#{{ id }}').val(JSON.stringify(values));
			}
			repaint{{ id }}();
		});

		function repaint{{ id }}() {
			$('#container{{ id }}').empty();
			values = [];
			try {
				var values = JSON.parse($('#{{ id }}').val());
			} catch (ex) {}
			for (var idx in values) {
				var itm = values[idx];
				$('#container{{ id }}').append(
					'<div>' +
						'<div class="example" style="width: 100%;">' +
							'<label style="display: none;">Heading</label>' +
							'<input style="display: none;" onchange="update{{ id }}();" type="text" name="title{{ id }}' + idx + '" style="width: 100%; margin-bottom: 15px;" value="' + itm.title + '"/>' +
							'<div class="tab-control">' +
								'<ul id="tabs{{ id }}' + idx + '" class="tabs"></ul>' + 
								'<div id="frames{{ id }}' + idx + '"class="frames"></div>' +
							'</div>' +
						'</div>' +
					'</div>'
				);
				for (var idx2 in _langs{{ id }}._data) {
					var itm2 = _langs{{ id }}._data[idx2];
					$('#tabs{{ id }}' + idx).append(
						'<li ' + ((idx2 == 0) ? 'class="active"' : '') + '>' +
							'<a href="#_page_{{ id }}' + idx + idx2 + '">' + itm2.title + '</a>' +
						'</li>'
					);
					
					var content = '';
					for (var idx3 in itm.blocks) {
						var itm3 = itm.blocks[idx3];
						if (itm3[itm2.urlFragment] != undefined) {
							content = itm3[itm2.urlFragment];
						}
					}
					$('#frames{{ id }}' + idx).append(
						'<div id="_page_{{ id }}' + idx + idx2 + '" class="frame">' +
							'<textarea class="ckeditor{{ id }}" data-lang="' + itm2.urlFragment + '" name="content{{ id }}' + idx + idx2 + '">' + content + '</textarea>' +
						'</div>'
					);
				}
			}
			
			$('.tab-control').tabcontrol();
//			$('#container{{ id }}').sortable();
			$('textarea').css('resize', 'vertical');
			$.each($('.ckeditor{{ id }}'), function(key, value) {
				CKEDITOR.replace($(value).attr('name'), {
					filebrowserBrowseUrl: '/secret/assets/?view=ckeditor',
					extraPlugins: 'autogrow',
				});
			});
			CKEDITOR.on("instanceReady", function(event) {
				event.editor.execCommand( 'autogrow' );
			});

			for (var i in CKEDITOR.instances) {
        CKEDITOR.instances[i].on('key', function() { setTimeout( function() { update{{ id }}(); }, 500); });
    	}
		};
		
		function update{{ id }}() {
			var result = [];
			$.each($('#container{{ id }}').children(), function(key, value) {
				var obj = {};
				obj.title = $(value).find('[name=title{{ id }}' + key + ']').val();
				obj.blocks = [];
				var block = {};
				$.each($(value).find('div.frames').children(), function(key, value) {
					block[$(value).find('textarea').attr('data-lang')] = CKEDITOR.instances[$(value).find('textarea').attr('name')].getData();
				});
				obj.blocks.push(block);
				result.push(obj);
			});
			$('#{{ id }}').val(JSON.stringify(result));
		};
	</script>
{% endblock cml_widget %}
